package org.dev.hi.hiui.banner.core;

import android.content.Context;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.viewpager.widget.PagerAdapter;

import org.dev.hi.hiui.banner.HiBanner;
import org.jetbrains.annotations.NotNull;

import java.util.List;

public
/**
 * Author WenPing 
 * CreateTime 2021/4/11.
 * Description:
 */

class HiBannerAdapter extends PagerAdapter {

    private Context mContext;
    private SparseArray<HiBannerViewHolder> mCacheViews = new SparseArray<>();
    private HiBanner.OnBannerClickListener mBannerClickListener;
    private IBindAdapter mBindAdapter;
    private List<? extends HiBannerMo> models;

    private boolean mAutoPlay = true;
    private boolean mLoop = false;
    private int mLayoutResId = -1;

    public HiBannerAdapter(Context context) {
        this.mContext = context;
    }

    /**
     * 让具体的业务去实现
     *
     * @param adapter
     */
    public void setBindAdapter(IBindAdapter adapter) {
        this.mBindAdapter = adapter;
    }

    public void setBannerData(@NotNull List<? extends HiBannerMo> data) {
        this.models = data;
        initCachedView();
        //刷新当前的数据
        notifyDataSetChanged();
    }

    public void setBannerClickListener(HiBanner.OnBannerClickListener bannerClickListener) {
        this.mBannerClickListener = bannerClickListener;
    }

    public void setAutoPlay(boolean mAutoPlay) {
        this.mAutoPlay = mAutoPlay;
    }

    public void setLoop(boolean mLoop) {
        this.mLoop = mLoop;
    }

    public void setLayoutResId(@LayoutRes int mLayoutResId) {
        this.mLayoutResId = mLayoutResId;
    }

    /**
     * 初始化数据
     */
    private void initCachedView() {
        mCacheViews = new SparseArray<>();
        for (int i = 0; i < models.size(); i++) {
            HiBannerViewHolder viewHolder = new HiBannerViewHolder(createView(LayoutInflater.from(mContext), null));
            mCacheViews.put(i, viewHolder);
        }
    }

    private View createView(LayoutInflater layoutInflater, ViewGroup parent) {
        //说明没设置布局id
        if (mLayoutResId == -1) {
            throw new IllegalArgumentException("you must set setLayoutResId first");
        }
        return layoutInflater.inflate(mLayoutResId, parent, false);
    }

    @Override
    public int getCount() {
        //实现无限轮播的关键
        return mAutoPlay ? Integer.MAX_VALUE : (mLoop ? Integer.MAX_VALUE : getRealCount());
    }

    /**
     * 通过取余的方式获得初次展示的item位置
     * 选取在Integer.Max的中间数值
     *
     * @return
     */
    public int getFirstItemPosition() {
        return Integer.MAX_VALUE / 2 - (Integer.MAX_VALUE / 2) % getRealCount();
    }

    /**
     * 获得真实的banner的items的数量
     *
     * @return
     */
    public int getRealCount() {
        return models == null ? 0 : models.size();
    }

    @Override
    public boolean isViewFromObject(@NonNull View view, @NonNull Object object) {
        return view == object;
    }


    @NonNull
    @Override
    public Object instantiateItem(@NonNull ViewGroup container, int position) {

        int realPosition = position;
        if (getRealCount() > 0) {
            realPosition = position % getRealCount();
        }

        HiBannerViewHolder viewHolder = mCacheViews.get(realPosition);
        if (container.equals(viewHolder.rootView.getParent())) {
            //把container中已经有的线移除
            container.removeView(viewHolder.rootView);
        }

        onBind(viewHolder, models.get(realPosition), realPosition);
        if (viewHolder.rootView.getParent() != null) {
            //确保viewHolder的rootView没有其他的子view
            ((ViewGroup) viewHolder.rootView.getParent()).removeView(viewHolder.rootView);
        }
        container.addView(viewHolder.rootView);
        return viewHolder.rootView;
    }

    private void onBind(final HiBannerViewHolder viewHolder, final HiBannerMo hiBannerMo, final int realPosition) {
        //给viewHolder设置点击事件
        viewHolder.rootView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (mBannerClickListener != null) {
                    mBannerClickListener.onBannerClick(viewHolder, hiBannerMo, realPosition);
                }
            }
        });
        if (mBindAdapter != null) {
            mBindAdapter.onBind(viewHolder, hiBannerMo, realPosition);
        }
    }

    @Override
    public int getItemPosition(@NonNull Object object) {
        /**
         * 让item每次都会刷新
         {@link #POSITION_NONE} if the item is no longer present
         * in the adapter.
         */
        return POSITION_NONE;
    }

    @Override
    public void destroyItem(@NonNull ViewGroup container, int position, @NonNull Object object) {
//        super.destroyItem(container, position, object);
    }

    /**
     * 创建 HiBannerAdapter 的holder类
     */
    public static class HiBannerViewHolder {

        private SparseArray<View> viewHolderSparseArr;

        View rootView;

        public HiBannerViewHolder(View rootView) {
            this.rootView = rootView;
        }

        public View getRootView() {
            return rootView;
        }

        public <T extends View> T findViewById(int id) {

            if (!(rootView instanceof ViewGroup)) {
                return (T) rootView;
            }
            if (this.viewHolderSparseArr == null) {
                this.viewHolderSparseArr = new SparseArray<>(1);
            }

            T childView = (T) viewHolderSparseArr.get(id);
            if (childView == null) {
                childView = rootView.findViewById(id);
                this.viewHolderSparseArr.put(id, childView);
            }
            return childView;
        }
    }
}
